package org.csu.onlineedubackend;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.MinioException;
import jakarta.annotation.PostConstruct;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

@SpringBootApplication
@MapperScan("org.csu.onlineedubackend.mapper")
@EnableScheduling
@EnableAspectJAutoProxy
public class OnlineEduBackendApplication {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.endpoint}")
    private String minioEndpoint;

    public static void main(String[] args) {
        SpringApplication.run(OnlineEduBackendApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://localhost:5173")
                        .allowedMethods("*")
                        .allowedHeaders("*");
            }
        };
    }
    
    @PostConstruct
    public void initMinIOBuckets() {
        // 定义所需的存储桶列表
        List<String> requiredBuckets = Arrays.asList(
            "images-bucket", 
            "videos-bucket", 
            "docs-bucket", 
            "audio-bucket", 
            "archives-bucket", 
            "others-bucket"
        );
        
        // 创建所有需要的存储桶
        for (String bucketName : requiredBuckets) {
            try {
                boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
                if (!found) {
                    System.out.println("创建 MinIO 存储桶: " + bucketName);
                    minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                    System.out.println("成功创建存储桶: " + bucketName);
                } else {
                    System.out.println("存储桶已存在: " + bucketName);
                }
            } catch (MinioException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
                System.err.println("创建 MinIO 存储桶失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
